package cn.naughtior.shch.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.GetResponse;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.io.IOException;
import java.util.HashMap;

/**
 * ${DESCRIPTION}
 *
 * @author shitou<shitou@in66.com>
 * @create 2016-12-20 11:48
 */

public class CustomRabbitTemplate extends RabbitTemplate {

    protected String queueName;
    protected String exchangeName;

    public CustomRabbitTemplate(ConnectionFactory connectionFactory) {
        super(connectionFactory);
    }

    public void init() throws IOException {
        Connection connection = null;
        Channel channel = null;
        try {
            connection = super.getConnectionFactory().createConnection();
            channel = connection.createChannel(false);
            channel.queueDeclare(queueName, true, false, false, new HashMap<String, Object>());
            channel.exchangeDeclare(exchangeName, "direct", true, false, new HashMap<String, Object>());
            channel.queueBind(queueName, exchangeName, "");
        } finally {
            if (null != channel) {
                channel.close();
            }
            if (null != connection) {
                connection.close();
            }
        }
    }

    public Message getMessageWithNoAutoAck() {
        return execute(new ChannelCallback<Message>() {
            @Override
            public Message doInRabbit(Channel channel) throws Exception {
                GetResponse response = channel.basicGet(queueName, false);
                if(null != response) {
                    return new Message(channel, response);
                }
                return null;
            }
        });
    }

    @Override
    public void setExchange(String exchange) {
        super.setExchange(exchange);
        this.exchangeName = exchange;
    }

    @Override
    public void setQueue(String queue) {
        super.setQueue(queue);
        this.queueName = queue;
    }

    public String getQueueName() {
        return queueName;
    }

    public void setQueueName(String queueName) {
        this.queueName = queueName;
    }

    public String getExchangeName() {
        return exchangeName;
    }

    public void setExchangeName(String exchangeName) {
        this.exchangeName = exchangeName;
    }
}

